package com.uiao.activemq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 订阅接收端 实现了监听器
 *
 * Created by cuihao on 2018/3/10.
 */
public class TopicConsumer {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageConsumer messageConsumer;
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);

        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createTopic("mq-topic");

            messageConsumer = session.createConsumer(destination);
            messageConsumer.setMessageListener(new MessageListener() {
                // 实现了一个监听器
                @Override
                public void onMessage(Message message) {
                    try {
                        MqBean mqBean = (MqBean) ((ObjectMessage) message).getObject();
                        System.out.println(mqBean);
                        if (null != message) {
                            System.out.println("收到消息 " + mqBean.getName());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
